﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web.Security;
using PInitiatives.Models;
using System.Net.Mail;
using PInitiatives.ViewModels.VMAccount;
using System.Web.Mvc.Html;
using PInitiatives.Helpers;

namespace PInitiatives.Controllers
{
    public class AccountController : Controller
    {
        PInitiativesEntities _db = new PInitiativesEntities();

        [Authorize]
        public ActionResult MyAccount()
        {
            string userName = Membership.GetUser(User.Identity.Name, true /* userIsOnline */).UserName;
            User u = _db.Users.Single(user => user.aspnet_Users.UserName == userName);
            VMAccountMyAccount avm = new VMAccountMyAccount();
            avm.ParticipedInitiatives = u.getParticipatedInitiatives("Participated").AsEnumerable<Initiative>().OrderBy(i => i.StartDate);
            avm.OwnedInitiatives = _db.Initiatives.Where(i => i.InitiativeAuthor.aspnet_Users.UserName == userName).OrderBy(i => i.StartDate);
            return View(avm);
        }

        //
        // GET: /Account/LogOn

        public ActionResult LogOn()
        {
            return View();
        }

        //
        // POST: /Account/LogOn

        [HttpPost]
        public ActionResult LogOn(LogOnModel model, string returnUrl/*Controller/Action/RequestUrl*/)
        {
            if (ModelState.IsValid)
            {
                if (Membership.ValidateUser(model.UserName, model.Password))
                {
                    FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe);
                    if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/")
                        && !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\"))
                    {
                        return Redirect(returnUrl);
                    }
                    else
                    {
                        return RedirectToAction("Index", "Home");
                    }
                }
                else
                {
                    ModelState.AddModelError("", "The user name or password provided is incorrect.");
                }
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }

        //
        // GET: /Account/LogOff

        public ActionResult LogOff()
        {
            FormsAuthentication.SignOut();

            return RedirectToAction("Index", "Home");
        }

        //
        // GET: /Account/Register

        public ActionResult Register()
        {
            return View();
        }

        //
        // GET: /Account/AcessDenied

        public ActionResult AccessDenied()
        {
            return View();
        }

        public ActionResult Profile(int id)
        {
            #region -> Mariusz ??
            //User user = null;
            //try
            //    {
            //        int UID = UserHelper.GetCurrentUserId();
            //        if (id == 0)
            //        {
            //            user = _db.Users.SingleOrDefault(u => u.ID == UID);
            //            ViewBag.MyAccount = true;
            //        }
            //        else
            //        {
            //            user = _db.Users.SingleOrDefault(u => u.ID == id);
            //            ViewBag.MyAccount = false;
            //        }                
            //}
            //catch (Exception)
            //{
            //    if (id == 0)
            //    {
            //        return RedirectToAction("Browse", "Initiative");
            //    }
            //    else
            //    {
            //        user = _db.Users.SingleOrDefault(u => u.ID == id);
            //        if (user != null)
            //        {
            //            ViewBag.MyAccount = false;
            //        }
            //        else
            //        {
            //            return RedirectToAction("Browse", "Initiative");
            //        }
                    
            //    }                
                
            //}

            //return View(user);
            #endregion

            try
            {
                User user = _db.Users.SingleOrDefault(u => u.ID == id);
                if (user.ID == UserHelper.GetCurrentUserId())
                    ViewBag.MyAccount = true;
                else
                    ViewBag.MyAccount = false;

                return View(user);
            }
            catch (Exception)
            {
                return RedirectToAction("Browse", "Initiative");
            }

        }


        public ActionResult AccountEdit(int id)
        {
            User user  = _db.Users.SingleOrDefault(u => u.ID == id);
            ViewBag.Faceboook = user.PostOnFB;
            ManageUserModel mum = new ManageUserModel(user.ID, user.FirstName, user.SecondName, user.LastName, user.Email, user.PostOnFB);
            return View(mum);
        }

        [HttpPost]
        public ActionResult AccountEdit(ManageUserModel mum)
        {
            User user = _db.Users.SingleOrDefault(u => u.ID == mum.ID);
            user.FirstName = mum.FirstName;
            user.SecondName = mum.SecondName;
            user.LastName = mum.LastName;
            user.PostOnFB = mum.Facebook;
            _db.SaveChanges();

            ViewBag.Faceboook = mum.Facebook;
            return RedirectToAction("Profile", new { id = user.ID });
        }

        //
        // GET: /Account/Verify
        public ActionResult Verify(string id)
        {
            Guid code = new Guid(id);
            AcceptanceList al = _db.AcceptanceLists.SingleOrDefault(a => a.Code == code);
            MembershipUser user = UserHelper.GetMembershipUserByUserId(al.UserID);
            if (user != null && user.IsApproved == false)
            {
                if (!user.IsApproved)
                {
                    user.IsApproved = true;
                    Membership.UpdateUser(user);
                }
                //FormsAuthentication.SetAuthCookie(user.UserName, false);
                ViewBag.MsgTitle = "Konto aktywowane";
                ViewBag.MsgBody = "Twoje konto zostało aktywowane, przejdz do strony ";
                ViewBag.LogOnLink = true;
            }
            else if (user != null && user.IsApproved == true)
            {
                ViewBag.MsgTitle = "Twoje konto zostało już aktywowane";
                //ViewBag.MsgBody = "Treść komunikatu";
                ViewBag.LogOnLink = false;
            }
            else 
            {
                ViewBag.MsgTitle = "Weryfikacja nie powiodła się";
                ViewBag.MsgBody = "Wystąpił problem z weryfikacją konta. Spróbuj ponownie, albo skontaktuj sie z administratorami";
                ViewBag.LogOnLink = false;
            }
            return View();
        }


        public ActionResult Activate()
        {
            return View();
        }
        
        //
        // POST: /Account/Register

        [HttpPost]
        public ActionResult Register(RegisterModel model)
        {
            if (ModelState.IsValid)
            {
                PInitiativesEntities db = new PInitiativesEntities();
                
                // Attempt to register the user
                MembershipCreateStatus createStatus;
                System.Web.Security.MembershipUser newAspUser = Membership.CreateUser(model.UserName, model.Password, model.Email, null, null, false, null, out createStatus);
                //if (!System.Web.Security.Roles.RoleExists("Administrator"))
                //    System.Web.Security.Roles.CreateRole("Administrator");
                

                if (createStatus == MembershipCreateStatus.Success)
                {
                    System.Web.Security.Roles.AddUserToRole(newAspUser.UserName, "Administrator");
                    //FormsAuthentication.SetAuthCookie(model.UserName, false /* createPersistentCookie */);

                    User user = new User(model.FirstName, model.SecondName, model.LastName, (Guid)newAspUser.ProviderUserKey);
                    db.Users.Add(user);
                    db.SaveChanges();
                    SendVerificationEmail(user);
                    return RedirectToAction("Activate", "Account");
                }
                else
                {
                    ModelState.AddModelError("", ErrorCodeToString(createStatus));
                }
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }

        //
        // GET: /Account/ChangePassword

        [Authorize]
        public ActionResult ChangePassword()
        {
            return View();
        }

        //
        // POST: /Account/ChangePassword

        [Authorize]
        [HttpPost]
        public ActionResult ChangePassword(ChangePasswordModel model)
        {
            if (ModelState.IsValid)
            {

                // ChangePassword will throw an exception rather
                // than return false in certain failure scenarios.
                bool changePasswordSucceeded;
                try
                {
                    MembershipUser currentUser = Membership.GetUser(User.Identity.Name, true /* userIsOnline */);
                    changePasswordSucceeded = currentUser.ChangePassword(model.OldPassword, model.NewPassword);
                }
                catch (Exception)
                {
                    changePasswordSucceeded = false;
                }

                if (changePasswordSucceeded)
                {
                    return RedirectToAction("ChangePasswordSuccess");
                }
                else
                {
                    ModelState.AddModelError("", "The current password is incorrect or the new password is invalid.");
                }
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }

        //
        // GET: /Account/ChangePasswordSuccess

        public ActionResult ChangePasswordSuccess()
        {
            return View();
        }

        private void SendVerificationEmail(User user)
        {
            string url = Request.Url.Authority;

            Guid code = Guid.NewGuid();
            AcceptanceList al = new AcceptanceList(code, user.ID, "Register", null);
            _db.AcceptanceLists.Add(al);
            _db.SaveChanges();
            string userEmail = _db.Users.Find(user.ID).Email;
            string subject = "[Portal inicjatyw] Witaj !";
            string body = "Twój link aktywacyjny: http://" + url + "/" + "Account/Verify/" + code.ToString();

            Email.SendEmail(userEmail, subject, body);
        }

        #region Status Codes
        private static string ErrorCodeToString(MembershipCreateStatus createStatus)
        {
            // See http://go.microsoft.com/fwlink/?LinkID=177550 for
            // a full list of status codes.
            switch (createStatus)
            {
                case MembershipCreateStatus.DuplicateUserName:
                    return "User name already exists. Please enter a different user name.";

                case MembershipCreateStatus.DuplicateEmail:
                    return "A user name for that e-mail address already exists. Please enter a different e-mail address.";

                case MembershipCreateStatus.InvalidPassword:
                    return "The password provided is invalid. Please enter a valid password value.";

                case MembershipCreateStatus.InvalidEmail:
                    return "The e-mail address provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidAnswer:
                    return "The password retrieval answer provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidQuestion:
                    return "The password retrieval question provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidUserName:
                    return "The user name provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.ProviderError:
                    return "The authentication provider returned an error. Please verify your entry and try again. If the problem persists, please contact your system administrator.";

                case MembershipCreateStatus.UserRejected:
                    return "The user creation request has been canceled. Please verify your entry and try again. If the problem persists, please contact your system administrator.";

                default:
                    return "An unknown error occurred. Please verify your entry and try again. If the problem persists, please contact your system administrator.";
            }
        }
        #endregion
    }
}
